CODE 81. N-Queens II

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/10/16/2013-10-16-CODE 81 N-Queens II/

访问原文「CODE 81. N-Queens II

Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public int totalNQueens(int n) {
// Note: The Solution object is instantiated only once and is reused by
// each test case.
int[] cols = new int[n];
for (int i = 0; i < n; i++) {
cols[i] = -1;
}
int number = createNQueens(n, cols, 0);
return number;
}
public int createNQueens(int n, int[] rows, int row) {
int number = 0;
for (int i = 0; i < n; i++) {
int j;
for (j = 0; j < row; j++) {
if (rows[j] == i || (row - j == Math.abs(rows[j] - i))) {
break;
}
}
if (j < row) {
continue;
}
rows[row] = i;
if (row == n - 1) {
rows[row] = -1;
return 1;
} else {
int tmp = createNQueens(n, rows, row + 1);
number += tmp;
}
rows[row] = -1;
}
return number;
}
Jerky Lu wechat
欢迎加入微信公众号